const Axios = require('axios');
const Path = require('path');
const Url = require('url');
const Fs = require('fs-extra');
const crypto = require('crypto');

const md5 = str => crypto.createHash('md5').update(str).digest('hex');

module.exports = async (dirname, url, ext = '.apk') => {
    if (dirname === 'icons') {
        const urlObj = Url.parse(url);
        ext = urlObj.pathname.match(/(\..*)(![^!]*)?$/)[1];
    }
    const pathname = Path.join(dirname, md5(url) + ext);
    const path = Path.join(__dirname, '../uploads', pathname);
    await Fs.ensureDir(path.replace(/\/[^\/]+$/, ''));
    const writer = Fs.createWriteStream(path);

    console.log('downloading...')
    const response = await Axios({
        url,
        method: 'GET',
        responseType: 'stream'
    })

    response.data.pipe(writer);

    return new Promise((resolve, reject) => {
        writer.on('finish', () => {
            console.log('downloaded.');
            resolve(pathname)
        })
        writer.on('error', (err) => {
            console.log(`download error. ${err.message}`);
            reject(err);
        })
    });
};
